package com.itheima.reggie.excetion;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 统一的处理违反数据库约束的异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R doSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException exception){
        /**
         * 业务异常:
         *      通知用户规范操作即可
         */
        log.info("用户操作异常:违反了数据库约束,{}"+exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")){
            String[] split = exception.getMessage().split("");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");

    }
}
